package dbtools;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;

import dbtools.structures.DBField;
import dbtools.structures.DBTable;


public class DBResultSet {

	private ResultSet rs=null;
	
	private ArrayList<DBField> selectedFields = new ArrayList<DBField>();
	
	public DBResultSet(ResultSet rs2, DBField[] selectedFields2) {
		this.rs = rs2;
		this.selectedFields.addAll(Arrays.asList(selectedFields2));
	}

	public boolean next() throws SQLException {
		return rs.next();
	}

	public<T extends DBTable> T get(Class<T> tableClass) throws SQLException {
		T tableInstance = DBFactory.createInstance(tableClass);
		get(tableInstance);
		return tableInstance;
	}
	
	public void get(DBTable table) throws SQLException{
		int pos = 0;
		for (DBField fld : selectedFields){
			pos ++;
			if (fld.getTable().getTableName().equals(table.getTableName())){
				DBField f = table.getFieldByName(fld.getName());
				f._setValueFromSQL(rs.getObject(pos));
			}
		}
	}

	public void close() {
		try{
			rs.close();
		}catch (Exception e) {
		}
	}

	public static void get(ResultSet rs, DBTable table) throws SQLException {
		for (Field f : table.getClass().getDeclaredFields()){
			if (DBField.class.isAssignableFrom(f.getType())){
				try {
					DBField fld;
					fld = (DBField) f.get(table);
					fld._setValueFromSQL(rs.getObject(f.getName()));
				} catch (IllegalArgumentException e) {
					throw new Error(e);
				} catch (IllegalAccessException e) {
					throw new Error(e);
				}
			}
		}
	}

}
